#include <iostream>
#include <pthread.h>
#include <unistd.h>

bool quit = false;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int cnt = 0;
const int num = 5;

void *Print(void *argc)
{
    char *name = (char *)argc;
    int count = 10;
    while (count--)
    {
        // 对于显示器就是临界资源：
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        std::cout << "I am " << name << std::endl;
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    pthread_mutex_lock(&mutex);
    cnt++;
    if (cnt == num)
        quit = true;
    pthread_mutex_unlock(&mutex);
    return argc;
}
int main()
{
    // 创建线程：
    pthread_t threads[num];
    for (int i = 0; i < num; i++)
    {
        char *name = new char[128];
        snprintf(name, 128, "thread-%d", i + 1);
        usleep(10000);
        pthread_create(threads + i, nullptr, Print, (void *)name);
    }

    // 唤醒：
    while (!quit)
    {
        std::cout << "唤醒一个线程：" << std::endl;
        pthread_cond_signal(&cond);
        sleep(1);
    }

    // 等待线程处理善后：
    for (auto &k : threads)
    {
        char *tmp = nullptr;
        pthread_join(k, (void **)&tmp);
        delete[] tmp;
    }
    return 0;
}